package com.juyu.miliao.api.service;

import com.juyu.miliao.api.cache.LikeLabelCache;
import com.juyu.miliao.api.constant.SexConstant;
import com.juyu.miliao.api.dao.mysql.LabelDao;
import com.juyu.miliao.api.dao.mysql.UserAssessLabelDao;
import com.juyu.miliao.api.dao.mysql.UserInfoDao;
import com.juyu.miliao.api.dao.mysql.UserLikeLabelDao;
import com.juyu.miliao.api.dao.redis.LineTimeRedisDao;
import com.juyu.miliao.api.dao.redis.UserCallRedisDao;
import com.juyu.miliao.api.domain.*;
import com.juyu.miliao.api.service.cache.LabelCacheService;
import com.juyu.miliao.api.util.UserAssignmentUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.Comparator.comparing;

@Service
@Slf4j
public class LabelService {

	@Resource
	private LabelDao labelDao;
	@Resource
	private LabelCacheService labelCacheService;
	@Resource
	private UserLikeLabelDao userLikeLabelDao;
	@Resource
	UserInfoDao userInfoDao;
	@Resource
    LineTimeRedisDao lineTimeRedisDao;
	@Resource
    UserCallRedisDao userCallRedisDao;
	@Resource
	private UserAssessLabelDao userAssessLabelDao;

	private final Logger labelLogger = LoggerFactory.getLogger("LabelService");

	public List<Label> getLabelCountByUserId(Long userId) {
		List<Label> list = labelDao.getLabelCountByUserId(userId);
		try {
			list.forEach(i->i.setLabelName(getLabelName(i.getLabelId())));
		}catch (Exception e){
			if(labelLogger.isErrorEnabled()){
				labelLogger.error(userId+"");
				labelLogger.error(e.getMessage());
			}

		}
		return list;
	}

	public List<Label> getLabelList(Integer sex) {
		if (sex == null) {
			return labelCacheService.getLabelList();
		}
		if (sex == SexConstant.MAN) {
			return getLabelWomenOrMan(sex) ;
		}
		return getLabelWomenOrMan(sex);
	}

	@Transactional(rollbackFor = Exception.class)
	public void insertUserLabel(int userId, String label) {
		if (label != null && !"".equals(label) && !"null".equals(label)) {
			if(label.contains(",")){
				String [] array = label.split(",");
				for(int i =0;i<array.length;i++){
					labelDao.insertUserLabel(userId,Integer.parseInt(array[i]));
				}
			}else{
				labelDao.insertUserLabel(userId,Integer.parseInt(label));
			}
			
		}
	}

	public void saveUserLikeLabel(Long userId, List<Long> ids) {
		UserLikeLabel userLikeLabel;
		for (Long id : ids) {
			LikeLabel value = LikeLabelCache.INSTANCE.getLabel(id);
			if (value == null) {
				throw new RuntimeException("id错误,标签不存在");
			}
			userLikeLabel = new UserLikeLabel();
			userLikeLabel.setLabelId(id);
			userLikeLabel.setUserId(userId);
			userLikeLabel.setLabelName(value.getName());
			userLikeLabelDao.saveUserLikeLabel(userLikeLabel, userId);
		}
	}

	public List<LikeLabel> listUserLikeLabel() {
		return LikeLabelCache.INSTANCE.getAllLabelList();
	}

	//获取标签名称
	public String getLabelName(Long labelId){
		Map<Long, Label> map = new HashMap<>();
		List<Label> labelList = labelCacheService.getLabelList();
		for(Label entity:labelList){
			map.put(entity.getLabelId(), entity);
		}
		return map.get(labelId).getLabelName();
	}
	//获取性别为女的标签
	public List<Label> getLabelWomenOrMan(int sex) {
		List<Label> labelList = labelCacheService.getLabelList();
		List<Label> list = new ArrayList<>();
		for (Label label : labelList) {
			if (label.getSex() == sex) {
				list.add(label);
			}
		}
		return list;
	}

	/**
	 * 添加自我评价
	 * @param userId
	 * @param list
	 */
	public void insertLabelForUserMeLabel(long userId, List<Long> list) {
		 User user = userInfoDao.getUserById(userId);
		 if(user.getIsHost() == 1){
			 List<UserMeLabel> userMeLabelList =labelDao.getUserIdForMeLable(userId);
			 if(userMeLabelList.size() !=0 ){
				 labelDao.delUserIdForMeLabel(userId);
			 }
			 for (long id:list) {
				 labelDao.insertLabelForUserMeLabel(userId,id);
			 }
		 }

	}
	//获取主播自我评价标签
	public List<Label> getLabelForMeLabel(long userId) {
		List<UserMeLabel> userIdMeLableList = labelDao.getUserIdForMeLable(userId);
		List<Label> list = new ArrayList<>();
		if(userIdMeLableList.size()>0){
			for(UserMeLabel userMeLabel:userIdMeLableList){
				Label label = new Label();
				label.setLabelId((long)userMeLabel.getLabelId());
				String labelName = getLabelName((long) userMeLabel.getLabelId());
				label.setLabelName(labelName);
				list.add(label);
			}
		}
		return list;
	}

    public List<User> getUserForLabel(String labelId) {
	    //获取在线主播
        Set<String> hostLine = lineTimeRedisDao.getHostLine();
        List<Long> userIdsList = new ArrayList<>();
        //获取带该标签的主播
        for (String userId:hostLine) {
           UserMeLabel userMeLabel =  labelDao.getUserIdForUserMeLabel(Long.valueOf(userId),labelId);
           if(userMeLabel!= null){
               userIdsList.add(userMeLabel.getUserId());
           }
        }
        if(userIdsList.size() == 0)
            return new ArrayList<User>();
        //获取用户信息
        List<User> list = userInfoDao.getUserForLabelByUserIds(userIdsList);
        //用户赋值
        for (User user: list) {
            UserAssignmentUtil.UserAssignment(user,lineTimeRedisDao,userCallRedisDao);
        }
        //列表排序（在线>接通率(降序)>魅力等级(降序)）
          list = list.stream().sorted(comparing(User::getIsLine)
                .thenComparing(comparing(User::getCallRate).reversed())
                .thenComparing(comparing(User::getmGrade).reversed())
        ).collect(Collectors.toList());
        return list;
    }

	public List<Label> getRedomLabelList(Integer sex, long id) {
		 List<UserMeLabel> userIdForMeLabel = labelDao.getUserIdForMeLable(id);
		List<Label> list = getLabelList(sex);
		if(userIdForMeLabel.size()>0){
			for(Label label :list){
				for (UserMeLabel userMeLabel:userIdForMeLabel) {
					if(label.getLabelId() == userMeLabel.getLabelId()){
						label.setIsChoose(2);
					}
				}
			}
		}
		return list;
	}

	public List<UserAssessLabel> getUserAssessLabel(long userId) {
		return  userAssessLabelDao.getUserAssessLabelToList(userId);
	}

	public void insertUserAssessLabel(long userId ,long insertUserId, String label) {
		UserAssessLabel userAssessLabel;
        userAssessLabelDao.delUserAssessLabel(userId, insertUserId);
		if (label != null && !"".equals(label) && !"null".equals(label)) {
			if (label.contains(",")) {

				String[] array = label.split(",");
				int length = array.length;
				if(length>3){
                    length =3;
                }
				for (int i = 0; i < length ; i++) {
					userAssessLabel = new UserAssessLabel();
					userAssessLabel.setUserId(userId);
					userAssessLabel.setInsertUserId(insertUserId);
					userAssessLabel.setLabelId(Integer.valueOf(array[i]));
					userAssessLabelDao.insertUserAssessLabel(userAssessLabel, userId);
				}
			} else {
				userAssessLabel = new UserAssessLabel();
				userAssessLabel.setInsertUserId(insertUserId);
				userAssessLabel.setLabelId(Integer.parseInt(label));
				userAssessLabelDao.insertUserAssessLabel(userAssessLabel, userId);
			}
		}
	}
}
